<template>
  <div class="shops">
    <div class="searchs">
      <div class="search_left">
        <span>关键字</span>
        <el-input
          class="sear_ipt"
          v-model="keywords"
          clearable
          placeholder="请输入商品名称或条形码"
        ></el-input>

        <span>分类名称</span>
        <el-input
          class="sear_ipt"
          v-model="type_name"
          clearable
          placeholder="请输入分类名称"
        ></el-input>

        <span>长保/短保</span>
        <el-select
          v-model="good_quality"
          class="radios"
          placeholder="请选择长保/短保"
        >
          <el-option label="长保" :value="1"> </el-option>
          <el-option label="短保" :value="2"> </el-option>
        </el-select>
        <el-button type="primary" @click="search">查询</el-button>
        <el-button @click="resetData">重置</el-button>
      </div>
      <el-button type="primary" @click="addShop">添加</el-button>
    </div>
    <el-table :data="shopList" border style="width: 100%">
      <el-table-column
        label="编号"
        prop="comm_id"
        width="100px"
      ></el-table-column>
      <el-table-column label="条形码" prop="code" width="150px">
      </el-table-column>
      <el-table-column label="缩略图">
        <template slot-scope="scope">
          <img class="shop_img" :src="scope.row.img" alt="" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" show-overflow-tooltip>
      </el-table-column>
      <el-table-column label="分类" prop="type_name"> </el-table-column>
      <el-table-column label="价格">
        <template slot-scope="scope">
          <span>¥ {{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="储存方式">
        <template slot-scope="scope">
          <span>{{ waysList[scope.row.storage] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="长保/短保">
        <template slot-scope="scope">
          <span>{{ saveLong[scope.row.good_quality] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期">
        <template slot-scope="scope">
          <span>{{ scope.row.shelf_life }}天</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            class="opt_btn"
            type="primary"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            class="opt_btn"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="currentChange"
      :current-page="page"
      :page-size="size"
      layout="total, prev, pager, next"
      :total="total"
      background
    ></el-pagination>

    <el-dialog
      :title="optType == '1' ? '添加' : '编辑'"
      :visible.sync="dialogEdit"
      width="45%"
      @close="closeModal"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
      >
        <el-form-item label="条形码" prop="code">
          <el-input v-model="ruleForm.code"></el-input>
        </el-form-item>
        <el-form-item label="缩略图" prop="img">
          <el-upload
            ref="imgupload"
            class="upload-demo"
            action
            :limit="1"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture"
            :http-request="uploadImg"
            accept=".jpg,.jpeg,.png"
          >
            <el-button size="small" type="primary" @click="clearFiles"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="type_id">
          <!-- <el-radio-group v-model.number="ruleForm.type_id">
            <el-radio :label="1">一级</el-radio>
            <el-radio :label="2">二级</el-radio>
            <el-radio :label="3">三级</el-radio>
          </el-radio-group> -->
          <el-cascader
            v-if="ifCase"
            :props="{
              expandTrigger: 'click',
              lazy: true,
              lazyLoad: getRender
            }"
            :placeholder="ruleForm.type_name"
            :show-all-levels="false"
            v-model.number="sel_type_id"
            @change="caschange"
            clearable
            style="width:100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="ruleForm.price"></el-input>
        </el-form-item>
        <el-form-item label="储存方式" prop="storage">
          <el-radio-group v-model="ruleForm.storage">
            <el-radio :label="1">常温</el-radio>
            <el-radio :label="2">冷藏</el-radio>
            <el-radio :label="3">FF</el-radio>
            <el-radio :label="4">冷冻</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="长保/短保" prop="good_quality">
          <el-radio-group v-model="ruleForm.good_quality">
            <el-radio :label="1">长保</el-radio>
            <el-radio :label="2">短保</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="保质期" prop="shelf_life">
          <el-input v-model="ruleForm.shelf_life"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "@/api/shopstore";
import { getToken } from "@/utils/auth";
export default {
  name: "shopList",
  data() {
    return {
      typeData: {
        1: "一级",
        2: "二级",
        3: "三级"
      },
      waysList: {
        1: "常温",
        2: "冷藏",
        3: "FF",
        4: "冷冻"
      },
      saveLong: {
        1: "长保",
        2: "短保"
      },
      shopList: [],
      keywords: "",
      page: 1,
      size: 10,
      total: 0,
      baseUrl: "https://www.xiandu001.com:81/",
      dialogEdit: false,
      ruleForm: {
        code: "",
        img: "",
        name: "",
        type_id: "",
        price: "",
        storage: 1,
        good_quality: 1,
        shelf_life: "",
        type_name: ""
      },
      rules: {
        code: [{ required: true, message: "请输入条形码", trigger: "blur" }],
        img: [{ required: true, message: "请上传商品图片", trigger: "blur" }],
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        shelf_life: [
          {
            required: true,
            message: "请输入商品保质期（天）",
            trigger: "blur"
          }
        ],
        type_id: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ],
        good_quality: [
          { required: true, message: "请选择长保/短保", trigger: "blur" }
        ],
        storage: [
          { required: true, message: "请选择储存方式", trigger: "blur" }
        ]
      },
      fileList: [],
      optType: "", //1.新增 2.编辑
      ifCase: false,
      type_path_id: [],
      sel_type_id: [], //回显id

      props: {
        lazy: true,
        that: this,
        async lazyLoad(node, resolve) {
          getRender(node, resolve);
        }
      },
      huixian: false,
      good_quality: "",
      type_name: ""
    };
  },
  created() {
    this.getListData();
  },
  methods: {
    async getRender(node, resolve) {
      const { level } = node;
      if (level === 0) {
        //一级选择器的生成
        let data = await api.getTypeList({
          page: "1",
          size: "100"
        });
        let nodes = Array.from(data.data.list).map(item => ({
          value: item.id,
          label: item.name
        }));
        resolve(nodes);
        // this.sel_type_id = [this.type_path_id[0]];
      } else if (level === 1) {
        // 二级选择器的生成
        // let id =
        //   this.huixian ? this.type_path_id[this.type_path_id.length - 1] : node.value;
        let data = await api.typeChildList({
          id: node.value
        });
        let nodes = Array.from(data.data).map(item => ({
          value: item.id,
          label: item.name,
          leaf: item.children.length > 0 ? level >= 2 : level >= 1,
          children: item.children.map(pp => ({
            value: pp.id,
            label: pp.name,
            leaf: level >= 1
          }))
        }));

        resolve(nodes);
        this.sel_type_id = [this.type_path_id[0], this.type_path_id[1]];
      } else if (level === 2) {
        resolve([]);
        let nodes = Array.from(node.children).map(item => ({
          value: item.id,
          label: item.name,
          leaf: level >= 1 // 设置为只有三级选择
        }));
        resolve(nodes);
        this.sel_type_id = this.type_path_id;
      }
    },
    // 详情
    getShopDetail(shopid) {
      api.shopDetail({ comm_id: shopid }).then(res => {
        let ids = res.data.type_path_id.split(",");
        this.type_path_id = ids.filter(item => !(item == ""));
        this.sel_type_id = [this.type_path_id[0]];
        this.huixian = this.type_path_id.length > 0 ? true : false;
      });
    },
    getListData() {
      let data = {
        keywords: this.keywords,
        good_quality: this.good_quality,
        type_name: this.type_name,
        page: this.page,
        size: this.size
      };
      api.getList(data).then(res => {
        const { list, count } = res.data;
        this.shopList = list;
        this.total = count;
      });
    },
    search() {
      this.page = 1;
      this.getListData();
    },
    uploadImg(obj) {
      const file = obj.file;
      const form = new FormData();
      form.append("file", file);
      form.append("token", getToken("token"));
      api.uploadImg(form).then(res => {
        const { url } = res.data;
        if (res.code == 200200) {
          this.ruleForm.img = this.baseUrl + url;
        } else {
          this.Message.error(res.msg);
        }
      });
    },
    currentChange(val) {
      this.page = val;
      this.getListData();
    },
    handleEdit(row) {
      this.dialogEdit = true;
      this.optType = "2";
      this.ruleForm = { ...row };
      this.fileList = [{ url: row.img }];
      setTimeout(() => {
        this.ifCase = true;
      }, 10);
      this.getShopDetail(row.comm_id);
    },
    addShop() {
      this.dialogEdit = true;
      this.optType = "1";
      this.ruleForm = {
        code: "",
        img: "",
        name: "",
        type_id: "",
        price: "",
        storage: 1,
        good_quality: 1,
        shelf_life: ""
      };
      this.sel_type_id = [];
      setTimeout(() => {
        this.ifCase = true;
      }, 10);
    },
    handleDelete(index, row) {
      this.$confirm("确定要永久删除此商品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          api
            .delCommo({ comm_id: row.comm_id })
            .then(res => {
              if (res.code == 200200) {
                this.$message.success(res.msg);
                this.getListData();
              }
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleRemove(file, fileList) {
      this.ruleForm.img = "";
    },
    clearFiles() {
      this.$refs["imgupload"].clearFiles();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = { ...this.ruleForm };
          data.type_id = this.type_path_id[this.type_path_id.length - 1];
          let fn =
            this.optType == "1" ? api.createCommo(data) : api.editCommo(data);
          fn.then(res => {
            if (res.code == 200200) {
              this.Message.success(res.msg);
              this.dialogEdit = false;
              this.getListData();
            } else {
              this.Message.error(res.msg);
            }
          }).catch(err => {
            this.Message.error(err.msg);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    closeModal() {
      this.$nextTick(() => {
        this.$refs["ruleForm"].clearValidate();
      });
    },
    caschange(e) {
      this.type_path_id = e;
      this.huxiian = false;
      this.ruleForm.type_id = e[e.length - 1];
    },
    resetData() {
      this.keywords = "";
      this.good_quality = "";
      this.type_name = "";
      this.page = 1;
      this.getListData();
    }
  }
};
</script>
<style lang="scss" scoped>
.shops {
  padding: 40px;
  .shop_img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }
  .searchs {
    margin-bottom: 20px;
  }
  .searchs,
  .search_left {
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 14px;
      color: #333;
    }
  }
  .sear_ipt {
    width: 200px;
    margin: 0 20px 0 10px;
  }
  input::-webkit-input-placeholder {
    color: #717171 !important;
  }
  input::-moz-placeholder {
    /* Mozilla Firefox 19+ */
    color: #717171 !important;
  }
  input:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 */
    color: #717171 !important;
  }
  input:-ms-input-placeholder {
    /* Internet Explorer 10-11 */
    color: #717171 !important;
  }
  .radios {
    margin-left: 15px;
    margin-right: 20px;
  }
}
</style>
